import 'package:boss/models/commodity.dart';
import 'package:boss/models/package_group.dart';
import 'package:flutter/material.dart';

class PackageGroupDetailProvider extends ChangeNotifier {
  PackageGroup packageGroup;

  bool get isEdit => packageGroup.id != null;

  List<CommodityFormList> get defaultedCommodityFormList => packageGroup.commodityFormList.where((item) => item.isDefaulted).toList();

  PackageGroupDetailProvider({this.packageGroup});

  setPackageGroupName(String groupName) {
    packageGroup.groupName = groupName;
    notifyListeners();
  }

  setPackageGroupCount(int count) {
    packageGroup.count = count;
    notifyListeners();
  }

  togglePackageGroupDuplicated() {
    packageGroup.duplicated = packageGroup.isDuplicated ? 0 : 1;
    notifyListeners();
  }

  setPackageGroupCommoditys(List<Commodity> commoditys) {
    var temp = commoditys.map((item) {
      var data = CommodityFormList.fromJson({
        'commodityId': item.id,
        'commodityName': item.title,
        'price': 0,
        'skuId': item.sku?.skuId,
        'skuName': item.sku?.skuName,
        'unit': item.unit,
      });

      var find = packageGroup.commodityFormList.firstWhere(
        (commodity) => commodity.commodityId == item.id && commodity.skuId == item.sku?.skuId,
        orElse: () => null,
      );

      if (find != null) {
        data.defaulted = find.defaulted;
      }

      return data;
    }).toList();

    packageGroup.commodityFormList = temp;
    notifyListeners();
  }

  removePackageGroupCommodity(CommodityFormList data) {
    packageGroup.commodityFormList.remove(data);
    notifyListeners();
  }

  setPackageGroupCommodityDefaulted(List<CommodityFormList> data) {
    packageGroup.commodityFormList.forEach((item) {
      item.defaulted = 0;
    });

    data.forEach((item) {
      item.defaulted = 1;
    });
    notifyListeners();
  }

  sortPackageGroupCommoditys(List<CommodityFormList> data) {
    packageGroup.commodityFormList = data;
    notifyListeners();
  }
}
